// 获取学生数据并渲染
function loadStudentData() {
    fetch('/api/students')
        .then(response => response.json())
        .then(data => {
            const container = document.getElementById('dataContainer');
            container.innerHTML = `<h3>提交记录</h3>
                <table>
                    <tr>
                        <th>小组</th>
                        <th>成员</th>
                        <th>答案</th>
                        <th>提交时间</th>
                    </tr>
                    ${data.map(item => `
                        <tr>
                            <td>${item.group_name || '个人'}</td>
                            <td>${item.student_names.split(',')}</td>
                            <td>第${currentQuestionIndex + 1}题: ${item['answer_' + (currentQuestionIndex + 1)]}</td>
                            <td>${new Date(item.created_at).toLocaleString()}</td>
                        </tr>
                    `).join('')}
                </table>
            `;
        });
}

// 初始化加载数据
window.addEventListener('load', () => {
    // 检查是否有保存的登录状态
    const savedUser = localStorage.getItem('currentUser');
    if (savedUser) {
        currentUser = JSON.parse(savedUser);
        document.getElementById('loginSection').style.display = 'none';
        document.getElementById('nameSelectSection').style.display = 'none';
        document.getElementById('welcomeSection').style.display = 'block';
        document.getElementById('welcomeMessage').textContent = `欢迎回来：${currentUser.names.join(', ')}`;
        
        // 如果当前有发布的题目，显示题目区域
        if (currentQuestion) {
            document.getElementById('questionSection').style.display = 'block';
            renderQuestion(currentQuestion);
        }
    } else {
        loadStudentData();
    }
    socket.on('questionChanged', () => {
        setTimeout(loadStudentData, 1000);
    });
});

// 确认姓名
function confirmNames() {
    const selectedDivs = document.querySelectorAll('#studentListContainer div._item-active_10gal_96');
    currentUser.names = Array.from(selectedDivs).map(div => div.textContent);
    
    // 新增格式验证
    if (!Array.isArray(currentUser.names) || currentUser.names.length === 0) {
        alert('请选择至少一个有效学生姓名');
        return;
    }
    
    // 保存用户信息到localStorage
    localStorage.setItem('currentUser', JSON.stringify(currentUser));
    
    loadStudentData();
}

// 添加登出功能
function logout() {
    localStorage.removeItem('currentUser');
    location.reload();
}